/**
* Slot machine
* Author: Saurabh Odhyan | http://odhyan.com
*
* Licensed under the Creative Commons Attribution-ShareAlike License, Version 3.0 (the "License")
* You may obtain a copy of the License at
* http://creativecommons.org/licenses/by-sa/3.0/
*
* Date: May 23, 2011 
*/
$(document).ready(function () {
    /**
    * Global variables
    */
    var completed = 0,
        imgHeight = 1110,
        posArr = [
            0,
            185,
            370,
            555,
            740,
            925
        ];

    /*
    var win = [];
    win[0] = win[454] = win[913] = 1;
    win[80] = win[539] = win[1000] = 2;
    win[165] = win[624] = win[1085] = 3;
    win[237] = win[696] = win[1157] = 4;
    win[310] = win[769] = win[1230] = 5;
    win[378] = win[837] = win[1298] = 6;
    */

    /**
    * @class Slot
    * @constructor
    */
    function Slot(el, max, step) {
        this.speed = 0; //speed of the slot at any point of time
        this.step = step; //speed will increase at this rate
        this.si = null; //holds setInterval object for the given slot
        this.el = el; //dom element of the slot
        this.maxSpeed = max; //max speed this slot can have
        this.pos = null; //final position of the slot    

        $(el).pan({
            fps: 30,
            dir: 'down'
        });
        $(el).spStop();
    }

    /**
    * @method start
    * Starts a slot
    */
    Slot.prototype.start = function () {
        var _this = this;
        $(_this.el).addClass('motion');
        $(_this.el).spStart();
        _this.si = window.setInterval(function () {
            if (_this.speed < _this.maxSpeed) {
                _this.speed += _this.step;
                $(_this.el).spSpeed(_this.speed);
            }
        }, 100);
    };

    /**
    * @method stop
    * Stops a slot
    */
    Slot.prototype.stop = function () {
        var _this = this,
            limit = 30;
        clearInterval(_this.si);
        _this.si = window.setInterval(function () {
            if (_this.speed > limit) {
                _this.speed -= _this.step;
                $(_this.el).spSpeed(_this.speed);
            }
            if (_this.speed <= limit) {
                _this.finalPos();
                $(_this.el).spSpeed(0);
                $(_this.el).spStop();
                clearInterval(_this.si);
                $(_this.el).removeClass('motion');
                _this.speed = 0;
            }
        }, 100);
    };

    /**
    * @method finalPos
    * Finds the final position of the slot
    */
    Slot.prototype.finalPos = function () {
        var el = this.el,
        pos,
        posMin = 2000000000,
        best,
        bgPos,
        i,
        j,
        k;

        el_id = $(el).attr('id');
        pos = document.getElementById(el_id).style.backgroundPosition;
        pos = pos.split(' ')[1];
        pos = parseInt(pos, 10);

        for (i = 0; i < posArr.length; i++) {
            for (j = 0; ; j++) {
                k = posArr[i] + (imgHeight * j);
                if (k > pos) {
                    if ((k - pos) < posMin) {
                        posMin = k - pos;
                        best = k;
                    }
                    break;
                }
            }
        }

        $(el).animate({
            backgroundPosition: "0 " + best + "px"
        }, {
            duration: 700,
            easing: 'linear',
            complete: function () {
                completed++;
            }
        });
    };

    /**
    * @method reset
    * Reset a slot to initial state
    */
    Slot.prototype.reset = function () {
        var el_id = $(this.el).attr('id');
        $._spritely.instances[el_id].t = 0;
        $(this.el).css('background-position', '0px 4px');
        this.speed = 0;
        completed = 0;
    };

    var applicationPath = location.protocol + '//' + location.hostname + "/badhshala/";

    //create slot objects
    var a = new Slot('#slot1', 30, 1),
        b = new Slot('#slot2', 45, 2),
        c = new Slot('#slot3', 70, 3);


    $("#jquery_jplayer_1").jPlayer({
        ready: function (event) {
            $(this).jPlayer("setMedia", {
                mp3: applicationPath + "/Content/spin-music.mp3",
                oga: applicationPath + "/Content/spin-music.ogg"
            });
        },
        supplied: "mp3, oga"
    });


    /**
    * Slot machine controller
    */
    $('#spin-btn').click(function () {

        if ($('#spin-btn').text() == 'SPIN') {

            $("#jquery_jplayer_1").jPlayer("play", 0);

            completed = 0;
            a.reset();
            a.start();
            b.reset();
            b.start();
            c.reset();
            c.start();

            disableControl();

            x = window.setInterval(function () {
                if (a.speed >= a.maxSpeed && b.speed >= b.maxSpeed && c.speed >= c.maxSpeed) {
                    window.clearInterval(x);
                }
            }, 100);
        }
        else if ($('#spin-btn').text() == 'STOP') {
            stopSlotmachine();
        }

    });

    function disableControl() {
        $('#spin-btn').text('wait..');

        setTimeout(function () {
            $('#spin-btn').text('STOP');
        }, 1000);
    }

    function stopSlotmachine() {
        $('#spin-btn').text('wait..');
        a.stop();
        b.stop();
        c.stop();

        x2 = window.setInterval(function () {
            if (a.speed == 0 && b.speed == 0 && c.speed == 0 && completed == 3) {
                window.clearInterval(x2);

                var slotAPosition = (parseInt($("#slot1").css('background-position').split(' ')[1], 10) % imgHeight) / 185;
                var slotBPosition = (parseInt($("#slot2").css('background-position').split(' ')[1], 10) % imgHeight) / 185;
                var slotCPosition = (parseInt($("#slot3").css('background-position').split(' ')[1], 10) % imgHeight) / 185;

                var finalResult = { SlotAPosition: slotAPosition, SlotBPosition: slotBPosition, SlotCPosition: slotCPosition };
                var postResultURL = applicationPath + "Home/PostResult";

                $.post(postResultURL, finalResult, function (response) {
                    printResult(response);
                    $("#jquery_jplayer_1").jPlayer("stop");
                    $('#spin-btn').text('SPIN');
                });
            }
        }, 100);
    }


    FB.init({
        appId: '535230306501368',
        cookie: true,
        status: true,
        xfbml: true
    });

    //invite friends 
    $("#invite-btn").click(function () {
        FB.ui({
            method: "apprequests",
            message: "win tickets to watch 'Badhshala', a Manoj Pandit Film"
        }, requestCallback);

    });

    var requestCallback = function (response) {
        var reportRequestURL = applicationPath + '/Home/SaveAppRequestsMade';
        var input = { 'totalRequests': response["to"].length };

        $.post(reportRequestURL, input, function (result) {
            printResult(result);
        });
    };

    //share results
    $("#share-btn").click(function () {
        FB.ui({
            method: 'feed',
            name: 'Hey, I just scored ' + $("#credit-info").text() + ' credits in Badhshala Jackpot.',
            caption: 'Badhshala Jackpot',
            description: (
             'Play Badhshala Jackpot and Win free ticket to the Badhshala movie.'
           ),
            link: 'https://apps.facebook.com/badhshala/',
            picture: 'https://badhshalajackpot.merocinema.com/Images/Saugat.JPG'
        },
       function (response) {
           if (response && response.post_id) {
               var reportRequestURL = applicationPath + '/Home/SavePostToWall';

               $.post(reportRequestURL, null, function (result) {
                   printResult(result);
               });
           }
       }
       );

    });


    //Enter Lottery
    $("#enter-lottery-btn").click(function () {
        //
        if ($('#enter-lottery-btn').hasClass('secondary-btn-disable') == false) {

            displayMessage("You have to post message to your wall in order to enter the lottery");

            setTimeout(function () {
                FB.ui({
                    method: 'feed',
                    name: 'Wow, I entered the lottery to win ticket to the movie Badhshala.',
                    caption: 'Badhshala Jackpot Movie Lottery',
                    description: (
             'Play Badhshala Jackpot and Win free ticket to the Badhshala movie.'
           ),
                    link: 'https://apps.facebook.com/badhshala/',
                    picture: 'https://badhshalajackpot.merocinema.com/Images/Arpan.JPG'
                },
       function (response) {
           if (response && response.post_id) {
               var reportRequestURL = applicationPath + '/Home/EnterLottery';

               $.post(reportRequestURL, null, function (result) {
                   if (result != null && result.FinalCredit != null) {
                       printResult(result);
                       displayMessage("You entered the Badhshala Movie Ticket Lottery. Stay Tuned.");
                   }
                   else {
                       displayMessage("Sorry, something went wrong. Please, try again.");
                   }
               });
           }
       })
            }, 2000);

        }
    });


    function printResult(result) {
        $("#credit-info").text(result.FinalCredit);

        if (result.CurrentWin > 0) {
            displayMessage("You won " + result.CurrentWin + " credits.");
        }
        else if (result.CurrentWin < 0) {
            displayMessage("You lost " + (-1) * result.CurrentWin + " credit.");
        }

        enableLotteryBtn(result.FinalCredit);
    }

    function enableLotteryBtn(credit) {
        if (credit >= 50) {
            $('#enter-lottery-btn').removeClass('secondary-btn-disable');
            $('#enter-lottery-btn').addClass('secondary-btn');
        }
        else {
            $('#enter-lottery-btn').addClass('secondary-btn-disable');
            $('#enter-lottery-btn').removeClass('secondary-btn');
        }
    }

    enableLotteryBtn($("#credit-info").text());

    function displayMessage(msg) {
        $('#message-content').text(msg);
        $('#message-content').show();
        $('#message-content').fadeOut(2000, 'linear');
    }

});
